var OrderTable = function () {
  var template = /*html*/ `
    <div class="order-table" v-loading.fullscreen.lock="loading">
      <template v-if="user!==null">
      <div class="orderTable" :class="{'hasPage':pagination.totalCount!==0}">
        <el-table fit stripe border :data="orders" style="width: 100%" :row-class-name="orderRowClassName" height="parent" @row-click="lookDetail">
          <checkbox-table-column ref="printCol" width="40px" :selectable="canPrint" check-field="id" @select-change="selectPrintOrder"
            fixed="left" align="center"></checkbox-table-column>
          <el-table-column :resizable="false" label="操作" column-key="handle" :auto-width="true" min-width="100px" fixed="left" header-align="center">
            <template slot-scope="scope">
              <template v-if="hasCreateOrderAuthority&&scope.row.status===1&&scope.row.isFinish===2">
                <el-button type="primary" size="mini" @click.stop="handleOrderClick(scope.row)">
                  生成外协返回单
                </el-button>
              </template>
              <template v-if="hasApprovalAuthority">
                <template v-if="scope.row.status===0">
                  <el-button type="primary" size="mini" @click.stop="updateStatus(scope.row,1)">审核</el-button>
                  <el-button type="danger" size="mini" @click.stop="updateStatus(scope.row,2)">退回</el-button>
                </template>
                <template v-else-if="scope.row.status===1">
                  <el-button v-if="scope.row.returnCount>0" type="danger" size="mini" @click.stop="retreatOutOrder(scope.row)">外协退回</el-button>
                </template>
              </template>

              <template v-if="hasFinishAuthority&&scope.row.status===1&&scope.row.isFinish===2">
                <el-button type="primary" size="mini" @click.stop="finishOrder(scope.row)">设置完成</el-button>
              </template>

              <template v-if="canDelete(scope.row)">
                <el-button type="danger" size="mini" @click.stop="deleteOrder(scope.row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="deptName" key="deptName" label="部门" min-width="120px" align="center"></el-table-column>
          <el-table-column :resizable="false" prop="companyOrderId" key="companyOrderId" label="订单编号" :auto-width="true" min-width="80px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" prop="factoryId" key="factoryId" label="工厂型号" :auto-width="true" min-width="80px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" prop="coustomId" key="coustomId" label="客户型号" :auto-width="true" min-width="80px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" prop="coustomOrderId" key="coustomOrderId" label="客户订单号" :auto-width="true" min-width="90px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" prop="supplierName" key="supplierName" label="供应商" :auto-width="true" min-width="70px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" prop="technology" key="technology" label="加工工艺" :auto-width="true" min-width="80px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" prop="flowCycle" key="flowCycle" label="流程周期" min-width="80px" align="center"></el-table-column>
          <el-table-column :resizable="false" prop="maching" key="maching" label="加工对象" :auto-width="true" min-width="70px" header-align="center">
            <template slot-scope="scope">
              <span v-if="!scope.row.hasEleOrder">{{scope.row.maching}}</span>
              <el-popover v-else title="电镀详情" trigger="hover" placement="right-start">
                <div slot="reference">
                  {{scope.row.maching}}(电镀)
                </div>
                <electroplate-detail :order="scope.row"></electroplate-detail>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="color" key="color" label="颜色" :auto-width="true" min-width="60px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" prop="model" key="model" label="规格" :auto-width="true" min-width="60px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" prop="count" key="count" label="外协数量" min-width="100px" align="center"></el-table-column>
          <el-table-column :resizable="false" prop="unitPrice" key="unitPrice" label="单价" min-width="100px" align="center"></el-table-column>
          <el-table-column :resizable="false" column-key="valuationCount" key="valuationCount" label="计价数量" min-width="100px" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.valuationCount}}{{scope.row.valuationUint}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="totalPrice" key="totalPrice" label="合计" min-width="100px" align="center"></el-table-column>
          <el-table-column :resizable="false" prop="remark" key="remark" label="备注" width="151px" show-overflow-tooltip header-align="center"></el-table-column>
          <el-table-column :resizable="false" column-key="isFinish" key="isFinish" label="是否完成" min-width="80px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg('outBusinessMgr.orderTable.isFinish.'+scope.row.isFinish)}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" column-key="returenTime" key="returenTime" label="完成时间" width="100px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.isFinish!==2&&scope.row.returenTime!==''">{{moment(scope.row.returenTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="returnCount" key="returnCount" label="完成数量" min-width="100px" align="center">
            <template slot-scope="scope">
              <div class="table-btn" @click.stop="lookRetreatDetail(scope.row)">{{scope.row.returnCount}}</div>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="returnValuationCount" key="returnValuationCount" label="完成计价数量" min-width="100px" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.returnValuationCount}} {{scope.row.valuationUint}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="createUser" key="createUser" label="制单人" :auto-width="true" min-width="80px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" column-key="createTime" key="createTime" label="制单时间" width="100px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.createTime!==''">{{moment(scope.row.createTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" column-key="status" key="status" label="状态" min-width="100px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg('outBusinessMgr.orderTable.status.'+scope.row.status)}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" column-key="approvalNameList" key="approvalNameList" label="可审核人" min-width="100px;" :auto-width="true" header-align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.approvalNameList">
                {{scope.row.approvalNameList.join(" ")}}
              </span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="approvalUser" key="approvalUser" label="审核人" :auto-width="true" min-width="80px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" column-key="approvalTime" key="approvalTime" label="审核时间" min-width="100px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.approvalTime!==''">{{moment(scope.row.approvalTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange">
      </table-pagination>
      </template>

      <el-dialog fullscreen title="外协单详情" :visible.sync="openDetailDialog" @closed="selectOrder=null">
        <div style="height:calc(100vh - 54px);overflow:auto;">
          <order-detail v-if="openDetailDialog" :order="selectOrder"></order-detail>
        </div>
      </el-dialog>

      <el-dialog fullscreen title="外协返回退回明细" :visible.sync="openRetreatDetailDialog" @closed="selectOrder=null">
        <div style="height:calc(100vh - 54px);overflow:auto;">
          <order-retreat-detail v-if="openRetreatDetailDialog" :order="selectOrder"></order-retreat-detail>
        </div>
      </el-dialog>

      <el-dialog title="外协退回" :visible.sync="openRetreatFormDialog" @closed="selectOrder=null" top="calc(50vh - 147px)">
        <div style="height:240px;overflow:auto;">
          <retreat-order-form v-if="openRetreatFormDialog" :order="selectOrder" @ensure="toRetreatOutOrder"></retreat-order-form>
        </div>
      </el-dialog>

      <el-dialog title="生成外协返回单" :visible.sync="openCreateOrderDialog" @closed="selectOrder=null" top="10vh" width="750px">
        <div style="height:calc(80vh - 54px);overflow:auto">
          <create-out-returnorder v-if="openCreateOrderDialog" :out-order="selectOrder" @save-success="createSuccess"></create-out-returnorder>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    mixins: [
      tablePaginationMixin(null)
    ],

    props: {
      orders: {
        type: Array,
        default: function () {
          return [];
        }
      },
      pagination: {
        type: Object,
        default: function () {
          return {
            currentPage: 1,
            totalCount: 0,
            pageSize: 10
          };
        }
      }
    },
    data: function () {
      return {
        loading: false,
        selectOrder: null,
        openDetailDialog: false,
        openRetreatDetailDialog: false,
        openRetreatFormDialog: false,
        openCreateOrderDialog: false,
        moment: moment,
        user: null,
        hasApprovalAuthority: false,
        hasUpdateActualPriceAuthority: false,
        hasCreateOrderAuthority: false,
        hasFinishAuthority:false
      };
    },
    created: function () {
      this.loading = true;
      var self = this;
      SysUtil.getUser().then(function (user) {
        self.hasApprovalAuthority = PermissionUtil.validateAuthorityByUser(user, 'putOutNew/approvalPutOutWarehouse');
        self.hasUpdateActualPriceAuthority = PermissionUtil.validateAuthorityByUser(user, 'putOutNew/updatePutOutActualPrice');
        self.hasCreateOrderAuthority = PermissionUtil.validateAuthorityByUser(user, 'putOutNew/returnPutOutOrder');
        self.hasFinishAuthority = PermissionUtil.validateAuthorityByUser(user, 'putOutNew/setPutOutOrderIsFinish');
        self.user = user;
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },
    methods: {
      updateStatus: function (order, operation) {
        var typeId = order.typeId;
        this.loading = true;
        var self = this;
        ajaxRequest('putOutNew/approvalPutOutOrder', {
          typeId: typeId,
          status: operation
        }).then(function (msg) {
          self.$alert(msg, '信息', {
            callback: function () {
              self.$emit('update-status');
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      retreatOutOrder: function (order) {
        this.selectOrder = order;
        this.openRetreatFormDialog = true;
      },

      toRetreatOutOrder: function (form, order) {
        var count = form.count;
        if (count === undefined) {
          this.$alert('请输入外协退回数量', '信息');
          return;
        }

        var valuationCount = form.valuationCount;
        if (valuationCount === undefined) {
          this.$alert('请输入外协退回计价数量', '信息');
          return;
        }

        this.loading = true;
        var self = this;
        ajaxRequest('putOutNew/backPutOutOrder', {
          typeId: order.typeId,
          backCount: count,
          valuationCount: valuationCount,
          remark: form.remark
        }).then(function () {
          self.loading = false;
          self.openRetreatFormDialog = false;
          self.$alert('外协退回成功', '信息', {
            callback: function () {
              self.$emit('retreat-success');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      deleteOrder: function (order) {
        var source = order.source;
        var self = this;
        if (source === 1) {
          this.$confirm('删除该外协单会删除相应的报工数据，是否删除？', '提示', {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning'
          }).then(function () {
            self.toDeleteOrder(order);
          }).catch(function () {});
          return;
        }
        this.toDeleteOrder(order);
      },

      toDeleteOrder: function (order) {
        this.loading = true;
        var self = this;
        ajaxRequest('putOutNew/deletePutOutOrder', {
          typeId: order.typeId
        }).then(function () {
          self.loading = false;
          self.$alert('外协单删除成功', '信息', {
            callback: function () {
              self.$emit('delete-order');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      finishOrder:function(order){
        this.loading = true;
        var self = this;
        ajaxRequest('putOutNew/setPutOutOrderIsFinish', {
          typeId: order.typeId
        }).then(function () {
          self.loading = false;
          self.$alert('外协单设置完成成功', '信息', {
            callback: function () {
              self.$emit('finish-order');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      pageChange: function () {
        this.$emit('page-change');
      },

      orderRowClassName: function (option) {
        var order = option.row;
        var isFinish = order.isFinish;
        var createTime = order.createTime;
        var flowCycle = order.flowCycle;

        var timeMoment = moment(createTime).add(flowCycle, 'day');
        var now;
        if (isFinish === 2) {
          now = moment();
        } else {
          var returenTime = order.returenTime;
          if (returenTime === '') {
            return '';
          }
          now = moment(returenTime);
        }
        if (moment(timeMoment).isBefore(now, 'day')) {
          return 'out-time';
        }

        if (moment(timeMoment).isSame(now, 'day') && isFinish === 2) {
          return 'out-time';
        }
        return '';
      },

      canDelete: function (order) {
        var status = order.status;
        if (status !== 2) {
          return false;
        }
        var user = this.user;
        return user.userName === order.createUser;
      },

      canPrint: function (order) {
        var status = order.status;
        return status === 1;
      },

      selectPrintOrder: function (selectIds, selectOrders) {
        this.$emit('select-print', selectIds, selectOrders);
      },

      toSelectRow: function (orders) {
        var ids = _.map(orders, 'id');
        this.$refs['printCol'].toggleRowSelection(ids, true);
      },

      clearRowSelect: function () {
        this.$refs['printCol'].clearSelect();
      },

      lookDetail: function (row, column) {
        var columnKey = column.columnKey;
        if (columnKey === 'handle') {
          return;
        }
        if (columnKey === 'actualPrice') {
          if (this.hasUpdateActualPriceAuthority && row.isFinish !== 2) {
            return;
          }
        }
        this.selectOrder = row;
        this.openDetailDialog = true;
      },

      lookRetreatDetail: function (row) {
        this.selectOrder = row;
        this.openRetreatDetailDialog = true;
      },

      toSaveActualPrice: function (order, option) {
        var actualPrice = option[0];
        var typeId = order.typeId;

        this.loading = true;
        var self = this;
        ajaxRequest('putOutNew/updatePutOutActualPrice', {
          typeId: typeId,
          actualPrice: actualPrice
        }).then(function () {
          self.loading = false;
          self.$alert('实际价格修改成功', '信息', {
            callback: function () {
              self.$emit('update-form-success');
            }
          })
        }).catch(function () {
          self.loading = false;
        });
      },

      handleOrderClick: function (order) {
        this.selectOrder = order;
        this.openCreateOrderDialog = true;
      },

      createSuccess: function () {
        this.openCreateOrderDialog = false;
      }
    },
    components: {
      CheckboxTableColumn: CheckboxTableColumn,
      OrderDetail: OrderDetail,
      OrderRetreatDetail: OrderRetreatDetail,
      RetreatOrderForm: RetreatOrderForm,
      UpdateFormPopover: UpdateFormPopover,
      CreateOutReturnorder: CreateOutReturnorder,
      ElectroplateDetail: ElectroplateDetail
    },
    template: template
  };
}();